package com.acme.bankapp.service.bank;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.exception.ClientExistsException;

/**
 * Created by alex on 8/24/14.
 */
public class BankServer {

	private ServerSocket providerSocket;
	private Socket connection = null;
	private String message;
	private BufferedWriter out;
	private BufferedReader in;
	private static Bank bank = new Bank();

	BankServer() {
	}

	void run() {
		try {
			// 1. creating a server socket
			providerSocket = new ServerSocket(1234, 10);
			// 2. Wait for connection
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			System.out.println("Connection received from " + connection.getInetAddress().getHostName());
			// 3. get Input and Output streams
			out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
			out.flush();
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			sendMessage("Connection successful");
			// 4. The two parts communicate via the input and output streams
			do {
				message = in.readLine();
				System.out.println("client>" + message);

				if (message.startsWith("add")) {
					try {
						BankService.addRecordIntoBank(message.substring(message.indexOf(' ') + 1, message.length()), bank);
                        sendMessage("Adding successful");
					} catch (ClientExistsException e) {
						sendMessage("Can't insert this record");
						e.printStackTrace();
					}

				}
				if (message.startsWith("delete")) {
					if (BankService.deleteClient(message.substring(message.indexOf(' ') + 1, message.length()), bank)){
						sendMessage("Deleting successful");
						continue;
					}
					
					sendMessage("Can't delete this client");
				}

			} while (!message.equals("exit"));
		} catch (IOException ioException) {
			ioException.printStackTrace();
		

		} finally {
			// 4: Closing connection
			try {
				in.close();
				out.close();
				providerSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.write(msg);
            out.newLine();
			out.flush();
			System.out.println("server>" + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(final String args[]) {

		BankServer server = new BankServer();
		while (true) {
			server.run();
		}
	}
}
